<template>
  <div class="user-container">
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcom' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- card区域 -->
    <el-card class="box-card">
      <!-- 搜索与添加用户 -->
      <el-row :gutter="50">
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="queryinfo.query" @change="getuserList" clearable>
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getuserList"
              @clear="getuserList"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="5">
          <el-button type="primary" @click="dialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 添加用户对话框 -->
      <el-dialog title="添加用户" :visible.sync="dialogVisible" width="50%" @close="addDialogClosed">
        <!-- 内主体表单 -->
        <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addForm.password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="addForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUser">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 修改用户对话框 -->
      <el-dialog
        title="修改用户"
        :visible.sync="editdialogVisible"
        width="50%"
        @close="editDialogClosed"
      >
        <!-- 内主体表单 -->
        <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="70px">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="editForm.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input v-model="editForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editdialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editUser">保 存</el-button>
        </span>
      </el-dialog>

      <!-- 分配角色对话框 -->
      <el-dialog
          title="分配角色"
          :visible.sync="setRoleDialogVisible"
          width="50%" @close="setRoleDialogVisibleClose">
          <div>
            <p>当前用户名: {{userInfo.username}}</p>
            <p>当前的角色: {{userInfo.role_name}}</p>
            分配角色：<el-select v-model="selectedRoleId" placeholder="请选择">
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id">
            </el-option>
          </el-select>
          </div>
          <span slot="footer" class="dialog-footer">
            <el-button @click="setRoleDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
          </span>
        </el-dialog>

      <!-- 用户列表 -->
      <el-table :data="userlist" border stripe fit>
        <el-table-column type="index" label="#" align="center"></el-table-column>
        <el-table-column prop="username" label="用户名" align="center"></el-table-column>
        <el-table-column prop="email" label="邮箱" align="center"></el-table-column>
        <el-table-column prop="mobile" label="电话" align="center"></el-table-column>
        <el-table-column prop="role_name" label="角色" align="center"></el-table-column>
        <el-table-column label="状态" align="center">
          <!-- 作用域插槽显示状态 -->
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="userStateChanged(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="235px" align="center">
          <template slot-scope="scope">
            <!-- 编辑修改用户 -->
            <el-button
              type="primary"
              @click="showEditDialog(scope.row.id)"
              icon="el-icon-edit"
              size="small"
            ></el-button>
            <!-- 删除用户 -->
            <el-button
              type="danger"
              @click="deleteUser(scope.row.id)"
              icon="el-icon-delete"
              size="small"
            ></el-button>
            <!-- 设置用户 -->
            <el-tooltip
              class="item"
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button type="warning" icon="el-icon-setting" size="small" @click="setRole(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryinfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryinfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>
  </div>
</template>

<script>
export default {
  name: "user-container",
  data() {
    //效验邮箱验证规则
    var checkEmail = (rule, value, cb) => {
      //验证邮箱正则
      const regEmail = /\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}/;
      if (regEmail.test(value)) {
        //合法的邮箱
        return cb();
      }
      cb(new Error("请输入合法的邮箱"));
    };
    //效验手机号验证规则
    var checkMobile = (rule, value, cb) => {
      //验证手机号正则
      const regMobile = /^1[3456789]\d{9}$/;
      if (regMobile.test(value)) {
        //合法的邮箱
        return cb();
      }
      cb(new Error("请输入正确的手机号"));
    };
    return {
      //获取用户列表参数
      queryinfo: {
        query: "",
        pagenum: 1,
        pagesize: 2
      },
      //获取用户
      userlist: [],
      total: 0,
      //添加用户弹框
      dialogVisible: false,
      //修改用户弹框
      editdialogVisible: false,
      //添加用户的表单数据
      addForm: {
        username: "",
        password: "",
        email: "",
        mobile: ""
      },
      //查询到用户的数据
      editForm: {},
      //添加用户的表单验证规则
      addFormRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "用户名在3~10个字符之间",
            trigger: "blur"
          }
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 6, max: 15, message: "密码在6~15个字符之间", trigger: "blur" }
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" }
        ],
        mobile: [
          { required: true, message: "请输入电话", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" }
        ]
      },
      //修改用户的表单验证
      editFormRules: {
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" }
        ],
        mobile: [
          { required: true, message: "请输入电话", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" }
        ]
      },
      //控制分配用户权限对话框
      setRoleDialogVisible : false,
      //需要被分配角色的用户信息
      userInfo:{},
      //获取的角色数据
      rolesList:[],
      //已选中的角色权限id
      selectedRoleId:""
    };
  },
  created() {
    //获取用户方法
    this.getuserList();
  },
  methods: {
    getuserList() {
      this.$http
        .get("users", { params: this.queryinfo })
        .then(res => {
          console.log(res);
          this.userlist = res.data.data.users;
          this.total = res.data.data.total;
        })
        .catch(err => {
          console.log(err);
        });
    },
    //监听pagesize的事件
    handleSizeChange(newSize) {
      //console.log(newSize);
      this.queryinfo.pagesize = newSize;
      this.getuserList();
    },
    //监听页码值的事件
    handleCurrentChange(newPage) {
      //console.log(newPage);
      this.queryinfo.pagenum = newPage;
      this.getuserList();
    },
    //监听switch的状态
    userStateChanged(userinfo) {
      //console.log(userinfo)
      this.$http
        .put(`users/${userinfo.id}/state/${userinfo.mg_state}`)
        .then(res => {
          return this.$message.success("更新用户状态成功!");
        })
        .catch(err => {
          userinfo.mg_state = !userinfo.mg_state;
          return this.$message.error("更新用户状态失败!");
        });
    },
    //监听添加用户对话框关闭事件
    addDialogClosed() {
      this.$refs.addFormRef.resetFields();
    },
    //监听修改用户对话框关闭事件
    editDialogClosed() {
      this.$refs.editFormRef.resetFields();
    },
    //添加用户效验：是否全部ok，然后再发起添加用户请求
    addUser() {
      this.$refs.addFormRef.validate(valid => {
        if (!valid) return;
        this.$http
          .post("users", this.addForm)
          .then(res => {
            this.dialogVisible = false;
            this.$message.success("添加用户成功");
            this.getuserList();
          })
          .catch(err => {
            this.dialogVisible = false;
            this.$message.success("添加用户失败");
          });
      });
    },
    //查询用户：根据用户id
    showEditDialog(id) {
      // console.log(id);
      this.$http
        .get("users/" + id)
        .then(res => {
          this.editForm = res.data.data;
        })
        .catch(err => {
          this.$message.Error("查询用户失败!");
        });
      this.editdialogVisible = true;
    },
    //修改用户信息提交请求
    editUser() {
      this.$refs.editFormRef.validate(valid => {
        if (!valid) return;
        this.$http
          .put("users/" + this.editForm.id, {
            email: this.editForm.email,
            mobile: this.editForm.mobile
          })
          .then(res => {
            this.editdialogVisible = false;
            this.$message.success("更新用户信息成功");
            this.getuserList();
          })
          .catch(err => {
            this.editdialogVisible = false;
            this.$message.success("更新用户信息失败");
          });
      });
    },
    //删除用户信息
    deleteUser(id) {
      //console.log(id);
      this.$confirm("此操作将永久删除该用户, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          //执行删除接口请求
          this.$http.delete("users/" + id, id).then(res => {
            this.getuserList();
          });
          this.$message({
            type: "success",
            message: "删除成功"
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    //分配用户权限方法
    setRole(userInfo){
      this.userInfo = userInfo;
      //在展示对话框之前获取所有的角色列表
      this.$http.get("roles").then((res)=>{
        this.rolesList = res.data.data
      }).catch((err)=>{
        return this.$message.error("获取角色失败")
      })
      this.setRoleDialogVisible = true;
    },
    //保存用户编辑权限的方法
    saveRoleInfo(){
      if(!this.selectedRoleId){
        this.$message.error("请选择要分配的角色")
      }
      this.$http.put(`users/${this.userInfo.id}/role`,{rid:this.selectedRoleId}).then((res)=>{
        this.$message.success("更新用户角色成功");
        this.getuserList();
        this.setRoleDialogVisible = false
      }).catch((err)=>{
        return this.$message.error("更新用户角色失败")
      })
    },
    //监听分配角色对话框的关闭事件
    setRoleDialogVisibleClose(){
      this.userInfo = {};
      this.selectedRoleId = ''
    }
  }
};
</script>

<style>
</style>